package controller;


import com.google.gson.Gson;
import domain.JobSeeker;
import service.impl.JobSeekerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet({"/register.do", "/login.do", "/checkAccount.do"})
public class JobSeekerLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");
        Gson gson = new Gson();
        PrintWriter out = response.getWriter();
        String uri = request.getRequestURI();
        String action = uri.substring(uri.lastIndexOf("/") + 1);
        HashMap<String, Object> hashMap = new HashMap<>();
        if ("login.do".equals(action)){
            String account = request.getParameter("account");
            String password = request.getParameter("password");
            JobSeekerServiceImpl ijs = new JobSeekerServiceImpl();
            JobSeeker js = ijs.jobSeekerLogin(account, password);
            if (js==null){
                hashMap.put("code",202);
                hashMap.put("msg","登陆失败，账户不存在");
            }else if (!js.getJspassword().equals(password)){
                hashMap.put("code",201);
                hashMap.put("msg","密码错误");
            }else {
                hashMap.put("jobSeeker",js);
                hashMap.put("code",200);
                hashMap.put("msg","登陆成功");
            }
            String str = gson.toJson(hashMap);
            out.print(str);

        }
        else if ("register.do".equals(action)){
            String account = request.getParameter("account");
            String password = request.getParameter("password");
            String name = request.getParameter("name");
            String tel = request.getParameter("tel");
            JobSeekerServiceImpl ijs = new JobSeekerServiceImpl();
            JobSeeker jobSeeker = new JobSeeker(account, password, name, tel);
            int i = ijs.addJobSeeker(jobSeeker);
            if (i>=0){
                hashMap.put("code",200);
                hashMap.put("msg","注册成功");
            }else {
                hashMap.put("code",201);
                hashMap.put("msg","注册失败");
            }
            String str = gson.toJson(hashMap);
            out.print(str);

        }

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);

    }
}
